﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EPiServer.Personalization.VisitorGroups;
using EPiServer.XForms.WebControls;
using System.Web;

namespace CriteriaPack.XFormsCriterion
{
        [VisitorGroupCriterion(
        Category = "Site Criteria",
        DisplayName = "Submitted Form",
        Description = "Criterion that checks if the visitor has submitted a specific xform in this session",
        LanguagePath = "/shell/cms/visitorgroups/criteria/xform")]
    public class XFormCriterion : CriterionBase<XFormModel>
    {
        public override bool IsMatch(System.Security.Principal.IPrincipal principal, System.Web.HttpContextBase httpContext)
        {
            if ((Model.SubmissionStatus == SubmissionStatus.HasNotSubmitted) ^ (httpContext.Session["Form_" + Model.SelectedXForm] != null)) 
                return true;

            return false;
        }

        public override void Subscribe(ICriterionEvents criterionEvents)
        {
            XFormControl.ControlSetup += new EventHandler(XFormControl_ControlSetup);
        }

        void XFormControl_ControlSetup(object sender, EventArgs e)
        {
            ((XFormControl)sender).AfterSubmitPostedData += new SaveFormDataEventHandler(XFormCriterion_AfterSubmitPostedData);
        }

        void XFormCriterion_AfterSubmitPostedData(object sender, SaveFormDataEventArgs e)
        {
            if (((XFormControl)sender).FormDefinition.Id.ToString() == Model.SelectedXForm)
            {
                HttpContext.Current.Session["Form_" + Model.SelectedXForm] = e.FormData;
            }
        }

        public override void Unsubscribe(ICriterionEvents criterionEvents)
        {
            XFormControl.ControlSetup -= new EventHandler(XFormControl_ControlSetup);
        }
    }
}
